package vn.scopionstudio.lockappandorid;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import vn.scopionstudio.lockappandorid.database.DBApp;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AlertDialog;
import android.app.Service;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.IBinder;
import android.view.WindowManager;
import android.widget.Toast;

public class AppLaunchCheckService extends Service {

	int updateInterval;
	private static ActivityManager am;
	// private LockMain main = new LockMain();
	private List<App> arrayApp = new ArrayList<App>();;
	public static String nameLastApp = "abc";
	ArrayList<String> listPackageName;
	DBApp mdb;
	private Handler handler;
	private Timer timer;
	public static boolean isCheck = false, isCheckFalse = false;
	String homeApp="";
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {

		super.onCreate();
		homeApp=PackageHomeName();
		arrayApp = loadInstalledApps(false);

		this.handler = new Handler();
		this.timer = new Timer();

		this.updateInterval = 1000;
		this.am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

		this.chekForRunningApps();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		return START_STICKY;
	}

	private void chekForRunningApps() {

		this.timer.scheduleAtFixedRate(new TimerTask() {

			@Override
			public void run() {
				handler.post(new Runnable() {

					@Override
					public void run() {
						
						mdb = new DBApp(getBaseContext());
						listPackageName = mdb.GetApp();
						if (listPackageName.size() > 0) {

							List<ApplicationInfo> packages;
							PackageManager pm;
							pm = getPackageManager();
							// get a list of installed apps.
							packages = pm.getInstalledApplications(0);
							try {
								ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
								// The first in the list of RunningTasks is
								// always
								// the foreground task.
								RunningTaskInfo foregroundTaskInfo = am
										.getRunningTasks(1).get(0);
								String foregroundTaskPackageName = foregroundTaskInfo.topActivity
										.getPackageName();
								if(foregroundTaskPackageName.equalsIgnoreCase("com.android.packageinstaller") && !isCheck){
									isCheck=true;	
									Intent i = new Intent(
												getBaseContext(),
												ShowDialog.class);
										i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
												| Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
										i.putExtra("NAME",
												foregroundTaskPackageName);
										startActivity(i);
									
									

								}
								
								if(foregroundTaskPackageName.equalsIgnoreCase(homeApp)){
									nameLastApp = "abc";
									isCheck=false;	
								}
								for (App appPk : arrayApp) {
									String targetPackage = appPk
											.getPackageName();

									if (foregroundTaskPackageName
											.equals(targetPackage)) {
										
										
										if (!(foregroundTaskPackageName
												.equalsIgnoreCase("vn.scopionstudio.lockappandorid"))) {
											if (!(foregroundTaskPackageName
													.equals(nameLastApp))) {
												if (listPackageName
														.contains(foregroundTaskPackageName)) {
													Intent i = new Intent(
															getBaseContext(),
															ShowDialog.class);
													i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
															| Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
													i.putExtra("NAME",
															foregroundTaskPackageName);
													startActivity(i);

												}

											}

										}

									}

								}
							} catch (Exception e) {
								e.printStackTrace();
								
							}

						}

					}
				});
			}
		}, 0, 200);

	}

	public void onPause() {

	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		if (this.timer != null) {
			this.timer.cancel();
			mdb.close();
		}
	}

	private ApkInfo getInfoFromPackageName(String pkgName) {
		ApkInfo newInfo = new ApkInfo();
		try {
			PackageInfo p = this.getPackageManager().getPackageInfo(pkgName,
					PackageManager.GET_PERMISSIONS);

			newInfo.setAppname(p.applicationInfo.loadLabel(
					this.getPackageManager()).toString());
			newInfo.setPname(p.packageName);
			newInfo.setVersionName(p.versionName);
			newInfo.setVersionCode(p.versionCode);
			// newInfo.setIcon(p.applicationInfo.loadIcon(this.getPackageManager()));
			newInfo.setP(p);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		return newInfo;
	}

	public static int findPIDbyPackageName(String packagename) {
		int result = -1;

		if (am != null) {
			for (RunningAppProcessInfo pi : am.getRunningAppProcesses()) {
				if (pi.processName.equalsIgnoreCase(packagename)) {
					result = pi.pid;
				}
				if (result != -1)
					break;
			}
		} else {
			result = -1;
		}

		return result;
	}

	boolean isPackageRunning(String packagename) {
		return findPIDbyPackageName(packagename) != -1;
	}

	private List<App> loadInstalledApps(boolean includeSysApps) {
		List<App> apps = new ArrayList<App>();

		// the package manager contains the information about all installed apps
		PackageManager packageManager = getPackageManager();

		List<PackageInfo> packs = packageManager.getInstalledPackages(0); // PackageManager.GET_META_DATA

		for (int i = 0; i < packs.size(); i++) {
			PackageInfo p = packs.get(i);
			ApplicationInfo a = p.applicationInfo;
			// skip system apps if they shall not be included
			if ((!includeSysApps)
					&& ((a.flags & ApplicationInfo.FLAG_SYSTEM) == 1)) {
				continue;
			}
			App app = new App();
			app.setTitle(p.applicationInfo.loadLabel(packageManager).toString());
			app.setPackageName(p.packageName);
			app.setVersionName(p.versionName);
			app.setVersionCode(p.versionCode);
			CharSequence description = p.applicationInfo
					.loadDescription(packageManager);
			app.setDescription(description != null ? description.toString()
					: "");
			apps.add(app);
		}
		return apps;
	}

	

	@Override
	public void onRebind(Intent intent) {
		// TODO Auto-generated method stub
		super.onRebind(intent);
	}

	public String PackageHomeName() {
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent,
				PackageManager.MATCH_DEFAULT_ONLY);
		return resolveInfo.activityInfo.packageName;
	}


}